package com.wc5818.controller;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.wc5818.service.WorkflowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/qiniu")
public class QiniuController {
    //构造一个带指定Zone对象的配置类
    Configuration cfg = new Configuration(Zone.zone1());
    //...其他参数参考类注释
    UploadManager uploadManager = new UploadManager(cfg);

    String accessKey = "ke7MrFXqZnJ3BxbOkGnPogJBvIhDT2-69qYaxumQ";
    String secretKey = "goHqzY5hF5o9RwGH2qtVYMeHBFweZyRvDsCDrhFj";
    String bucket = "wc-wx-img";

    Auth auth = Auth.create(accessKey, secretKey);

    //String localFilePath = "/Users/liudh/Desktop/WechatIMG383.jpeg";
    //默认不指定key的情况下，以文件内容的hash值作为文件名
    String key = null;

    @PostMapping("/upload")
    public Object upload(@RequestParam("file") MultipartFile file) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", false);
        try {
            String upToken = auth.uploadToken(bucket);
            Response response =  uploadManager.put(file.getInputStream(), key, upToken,null,null);

            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

            map.put("success", true);
            map.put("downloadPath", "http://img.wc5818.com/" + putRet.key);

        } catch (QiniuException ex) {
            Response r = ex.response;
            map.put("errorMsg", r.toString());
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        return map;
    }

}
